<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="选择题目"
    width="1000px"
    @ok="handleSubmit"
    destroyOnClose
  >
    <!-- 筛选区域 -->
    <div class="filter-container" style="margin-bottom: 16px;">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="题目类型">
            <a-select
              v-model:value="filterParams.isPublic"
              placeholder="请选择题目类型"
              allow-clear
              @change="handleFilterChange"
            >
              <a-select-option :value="0">计分题</a-select-option>
              <a-select-option :value="1">基础信息题</a-select-option>
              <a-select-option :value="2">调查问卷题</a-select-option>
              <a-select-option :value="3">关联题</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="题目内容">
            <a-input
              v-model:value="filterParams.content"
              placeholder="请输入题目内容"
              allow-clear
              @keyup.enter="handleFilterChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item>
            <a-button type="primary" @click="handleFilterChange" preIcon="ant-design:search-outlined">查询</a-button>
            <a-button style="margin-left: 8px" @click="handleReset" preIcon="ant-design:reload-outlined">重置</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </div>

    <!-- 题目列表 -->
    <BasicTable
      @register="registerTable"
      :rowSelection="rowSelection"
      :useSearchForm="false"
      :showTableSetting="false"
      :bordered="true"
      :canResize="false"
    >
      <template #tableTitle>
        <span>已选择 {{ selectedRowKeys.length }} 道题目</span>
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, unref, toRaw } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { list } from '../ExamQuestions.api';
  import { columns } from '../ExamQuestions.data';

  // 选择弹窗专用的列配置
  const selectColumns = [
    {
      title: '题目内容',
      align: "center",
      dataIndex: 'content'
    },
    {
      title: '是否为多选题',
      align: "center",
      dataIndex: 'isMultipleChoice',
      customRender: ({ text }) => (text === 0 ? '否' : '是'),
    },
    {
      title: '题目分值',
      align: "center",
      dataIndex: 'valueOfScore'
    },
    {
      title: '正确答案',
      align: "center",
      dataIndex: 'correctAnswer'
    },
    {
      title: '题目类型',
      align: "center",
      dataIndex: 'isPublic',
      customRender: ({ text }) => {
        if (text === 0) {
            return '计分题';
        } else if (text === 1) {
            return '基础信息题';
        } else if (text === 2) {
            return '调查问卷题';
        } else if (text === 3) {
          return '关联题';
        }
      },
    },
  ];

  // 声明Emits
  const emit = defineEmits(['select', 'register']);

  const props = defineProps({
    par_id: {
      type: Number,
      required: true
    }
  });

  const selectedRowKeys = ref<Array<string | number>>([]);
  const filterParams = reactive({
    isPublic: undefined,
    content: '',
    bankId: props.par_id
  });

  // 监听props.par_id的变化
  watch(() => props.par_id, (newVal) => {
    filterParams.bankId = newVal;
  });

  // 注册弹窗
  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    // 如果有预选的数据，设置选中状态
    if (data && data.selectedQuestions) {
      selectedRowKeys.value = data.selectedQuestions.map(item => item.id);
    } else {
      selectedRowKeys.value = [];
    }
  });

  // 注册表格
  const [registerTable, { reload, getDataSource }] = useTable({
    api: list,
    rowKey: 'id',
    columns: selectColumns,
    formConfig: {
      labelWidth: 60,
      baseRowStyle: { maxHeight: '20px' },
    },
    striped: true,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
    beforeFetch: (params) => {
      // 合并筛选参数
      return Object.assign(params, filterParams);
    },
  });

  /**
   * 选择列配置
   */
  const rowSelection = {
    type: 'checkbox',
    columnWidth: 50,
    selectedRowKeys: selectedRowKeys,
    onChange: onSelectChange,
  };

  /**
   * 选择事件
   */
  function onSelectChange(selectedKeys: (string | number)[]) {
    selectedRowKeys.value = selectedKeys;
  }

  /**
   * 筛选变化事件
   */
  function handleFilterChange() {
    reload();
  }

  /**
   * 重置筛选
   */
  function handleReset() {
    filterParams.isPublic = undefined;
    filterParams.content = '';
    reload();
  }

  // 提交事件
  function handleSubmit() {
    setModalProps({ confirmLoading: true });
    
    // 获取表格数据源
    const dataSource = getDataSource();
    
    // 获取选中的行数据
    const selectedRows = dataSource.filter(item => 
      selectedRowKeys.value.includes(item.id)
    );

    // 关闭弹窗
    closeModal();
    
    // 触发选择事件
    emit('select', toRaw(selectedRows));
    
    setModalProps({ confirmLoading: false });
  }
</script>

<style lang="less" scoped>
  .filter-container {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
    border: 1px solid #d9d9d9;
  }
</style>
